package com.zjitc.backend_shop.controller.User;

import com.zjitc.backend_shop.pojo.Admin;
import com.zjitc.backend_shop.pojo.User;
import com.zjitc.backend_shop.service.UserService;
import com.zjitc.backend_shop.utils.APIResponse;
import com.zjitc.backend_shop.utils.CheckResult;
import com.zjitc.backend_shop.utils.JwtUtils;
import com.zjitc.backend_shop.utils.Token;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 王新瑜
 * @date 2024/12/20 15:24
 */
@Tag(name = "角色管理")
@Controller
@RestController
@RequestMapping("/home")
public class UserController {
    @Autowired
    private UserService userService;
    @Operation(summary = "用户登录")
    @RequestMapping("/login")
    public APIResponse<Token> login(@RequestBody User user) {
        APIResponse apiResponse = new APIResponse();
        if (userService.login(user.getUsername(), user.getPassword())) {
            apiResponse.setData(new Token());
            String token = JwtUtils.generateToken(user.getUsername());
            apiResponse.APIResponseOK(0, "登录成功", new Token(token));
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "用户名或密码有误！", null);
            return apiResponse;
        }
    }
    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public APIResponse register(@RequestBody User user) {
        APIResponse apiResponse = new APIResponse();
        user.setSalt("ItCast");
        if (userService.addUser(user)) {
            apiResponse.APIResponseOK(0, "注册成功", null);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "注册失败", null);
            return apiResponse;
        }
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/user")
    public APIResponse<User> findUser(HttpServletRequest request) {
        String token = request.getHeader("jwt");
        Claims claims = JwtUtils.validateToken(token);
        APIResponse apiResponse = new APIResponse();
        User user1 = userService.findByUsername(claims.getSubject());
        if (user1 != null) {
            user1.setPassword(null);
            apiResponse.APIResponseOK(0, "查询成功", user1);
            return apiResponse;
        } else {
            apiResponse.APIResponseError(1000, "查询失败", null);
            return apiResponse;
        }
    }
    @Operation(summary = "获取用户列表")
    @GetMapping("/user/list")
    public APIResponse<List<User>> findAdminAll(HttpServletRequest request) {
        List<User> users =userService.findAllUser();
        APIResponse<List<User>> apiResponse = new APIResponse<>(0, "", users);
        return apiResponse;
    }

}
